package controllers.service;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import enumerators.Tables;
import models.domain.Contract;
import models.domain.ContractItem;
import models.persistence.JPAUtil;
import models.persistence.StaticQuerries;

public class ManageSubscriptionsService {

	private Contract contract;
	private EntityManager em;

	public ManageSubscriptionsService() {
		em = JPAUtil.createEntityManager();
	}

	/**
	 * Ανακτά όλα τα διαθέσιμα πακέτα
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<ContractItem> getAvailableSubscriptions() {
		List<ContractItem> subscriptions = null;

		subscriptions = (List<ContractItem>) (Object) StaticQuerries
				.getAllItems(em, Tables.ContractItem);

		return subscriptions;
	}

	/**
	 * Ανακτά όλα τα πακέτα που έχει ενεργοποιήσει ο πελάτης στο συμβόλαιό του
	 * 
	 * @param contractId
	 * @return
	 */
	public List<ContractItem> getContractSubscriptions(int contractId) {

		List<ContractItem> subscriptions = null;

		try {
			contract = em.find(Contract.class, contractId);
		} catch (NoResultException ex) {
			contract = null;
		}

		subscriptions = contract.getContractItem();

		return subscriptions;
	}

	/**
	 * Προσθέτει ένα νέο πακέτο στο συμβόλαιο του πελάτη
	 * 
	 * @param contractId
	 * @param subscriptionId
	 * @return
	 */
	// TODO need to correct to be able to add more than one contractItem to
	// Contract
	public boolean addContractSubscription(int contractId, int subscriptionId) {

		ContractItem subscription = new ContractItem();

		subscription = em.find(ContractItem.class, subscriptionId);

		List<ContractItem> subscriptions = new LinkedList<ContractItem>();

		subscriptions.add(subscription);

		contract = em.find(Contract.class, contractId);

		contract.setContractItem(subscriptions);

		if (contract != null) {
			em.persist(contract);

			return true;
		}

		return false;

	}

}
